package app.common.utils;

import app.common.utils.cjt.ao.WmsStockStockSyncByPdAo;
import app.common.utils.cjt.vo.InventoryClassQueryVo;
import app.common.utils.cjt.vo.InventoryStatementVo;
import app.common.utils.cjt.vo.WarehouseYiDaVo;
import app.common.utils.dingtalk.Auth2Utils;
import app.common.utils.dingtalk.Config;
import app.common.utils.dingtalk.YiDaUtils;
import app.common.utils.dingtalk.domain.SearchCondition;
import app.v1.yd.domain.pojo.YdInventoryStatement;
import com.aliyun.dingtalkyida_1_0.models.BatchGetFormDataByIdListResponseBody;
import com.aliyun.dingtalkyida_1_0.models.GetFormDataByIDResponseBody;
import com.gitee.feizns.dynamic.DateUtils;
import com.gitee.feizns.dynamic.Lists;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * 钉钉Api常量（维康）
 * @author feizns
 * @since 2022/11/9
 */
public interface YdApi {

    /**
     * 配置
     */
    Config config = new Config() {{
//        this.setAgentId(2446942339L);
        this.setAppKey("dingm4hzxpe9afsyevat");
        this.setAppSecret("b6vi6hlamn_vUqvgfDjVnYZvYhAayQfTFxfarkcm7LpkuZGocczoLctuC2IIyjfZ");
//        this.setApiToken("0917ffe283e63da39b88d965b55ddb90");
        this.setSystemToken("4J966K71SOL2JYP96E0RZ489U6SJ2BA2UC66LC");
        this.setAppType("APP_FNOSB1AQ3LRP8VAZETLR");
        this.setCorpId("ding808f671b9e1af81635c2f4657eb6378f");
        this.setUserId("16593145555457735");
//        this.setUserId("294601221159348");
    }};

    /**
     * dingDing accessToken
     */
    Auth2Utils auth2Utils = new Auth2Utils(config);

    /**
     * 宜搭工具类
     */
    YiDaUtils yiDaUtils = new YiDaUtils(auth2Utils);

    /**
     * 删除
     */
    static void deleteYiDaUtils(String fromUuid, SearchCondition condition) {
        List<String> instanceIds = yiDaUtils.forms.instanceIds(fromUuid, condition);
        System.out.println("删除：实例：" + instanceIds);
        List<List<String>> partition = Lists.partition(instanceIds, 500);
        for (List<String> ids : partition)
            yiDaUtils.forms.deleteByIds(fromUuid, ids.toArray(new String[]{}));
    }

    /**
     * 删除指定区间内的  FORM-33666CB1LI646OZXEQL078UISU4D2PEP0RD9LX2 数据
     * @param startDate 开始日期
     * @param endDate 结束日期
     */
    static void deleteYiDaUtils(LocalDate startDate, LocalDate endDate) {
        while ( startDate.isBefore(endDate) ) {
            String format = DateUtils.format(startDate, "yyyy-MM-dd");
            SearchCondition condition = SearchCondition.textEq("textField_laxmswy0", format);
            deleteYiDaUtils("FORM-33666CB1LI646OZXEQL078UISU4D2PEP0RD9LX2", condition);
            System.out.println("已删除日期：" + format);
            startDate = startDate.plusDays(1);
        }
    }

    /**
     * 删除指定区间内的  FORM-33666CB1LI646OZXEQL078UISU4D2PEP0RD9LX2 数据
     * @param startDate 开始日期
     * @param endDate 结束日期
     */
    static void deleteYiDaUtilsGroupByWarehouseNo(LocalDate startDate, LocalDate endDate) {
        while ( startDate.isBefore(endDate) ) {
            String format = DateUtils.format(startDate, "yyyy-MM-dd");
            SearchCondition condition = SearchCondition.textEq("textField_laxmswy0", format);
            deleteYiDaUtils("FORM-Y6666RA12JPAW7LMFYYT543K2P8Y2J9OOQPHLG", condition);
            System.out.println("已删除日期：" + format);
            startDate = startDate.plusDays(1);
        }
    }

//    public static void main(String[] args) {
//
//    }

//    static void main(String[] args) {
//        LocalDate startDate = LocalDate.of(2023, 4, 1);
//        LocalDate endDate = LocalDate.of(2023, 7, 23);
//        deleteYiDaUtils(startDate, endDate);
//        deleteYiDaUtilsGroupByWarehouseNo(startDate, endDate);
//    }

//    public static void main(String[] args) {
//        yiDaUtils.forms.clear("FORM-FDA66N81XTS94LNBB4C9879UH2HC27IJGAAGL1");
////        yiDaUtils.forms.instanceIds("FORM-FDA66N81XTS94LNBB4C9879UH2HC27IJGAAGL1", null, null, id -> {
////            Retry.setting(100).execute(() -> {
////                yiDaUtils.forms.deleteByIds("FORM-FDA66N81XTS94LNBB4C9879UH2HC27IJGAAGL1", id);
////                System.out.println("删除数据：" + id);
////            });
////        });
////        List<String> list = yiDaUtils.forms.instanceIds("FORM-Z2666J810PK2TK7J6G5425QYSMYE2RB2UC66LI3");
////        System.out.println(list);
////        GetFormDataByIDResponseBody forms = yiDaUtils.forms.getById("FINST-G9766T7197HAGV1IEPPEE9G7SU4W3QF6LNHHLW7H1");
////        System.out.println(JSON.toJSONString(forms.getFormData()));
//    }

    /**
     * 库存类
     * @return {@link List}<{@link InventoryClassQueryVo}>
     */
    static List<InventoryClassQueryVo> inventoryClass() {
        return YdApi.yiDaUtils.forms.getList("FORM-YU966T91OJH9G33C8WYU9BRJ64KB31UAH5WFLF").stream().map(data -> {
            InventoryClassQueryVo vo = new InventoryClassQueryVo();
            vo.setCode((String) data.getFormData().get("textField_lfw5hdbm"));
            vo.setName((String) data.getFormData().get("textField_lfw5hdbo"));
            vo.setParentCode((String) data.getFormData().get("textField_lg04zx0v"));
            vo.setParentName((String) data.getFormData().get("textField_lg04zx0x"));
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 仓库列表
     * @return {@link List}<{@link WarehouseYiDaVo}>
     */
    static List<WarehouseYiDaVo> warehouses()  {
        List<BatchGetFormDataByIdListResponseBody.BatchGetFormDataByIdListResponseBodyResult> list =
                yiDaUtils.forms.getList("FORM-Z2666J810PK2TK7J6G5425QYSMYE2RB2UC66L06");
        return list.stream().map(result -> {
            Map<String, ?> data = result.getFormData();
            WarehouseYiDaVo vo = new WarehouseYiDaVo();
            vo.setNo((String) data.get("textField_l8jvme8e"));
            vo.setName((String) data.get("textField_l5c08n9x"));
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * @param consumer {@link Consumer}
     */
    static void inventoryStatement(Consumer<GetFormDataByIDResponseBody> consumer) {
        yiDaUtils.forms.instanceIds("FORM-NC966W81ZEV5BRNEAHUXI6725MJ12NKTOZBBL92",
                null,
                null,
                null,
                null,
                id -> consumer.accept(yiDaUtils.forms.getById(id)),
                SearchCondition.textEq("textField_lben36ay", "0")
        );
    }

    /**
     * @param consumer {@link Consumer}
     */
    static void inventoryStatement(LocalDateTime modifiedFromTimeGMT, Consumer<GetFormDataByIDResponseBody> consumer) {
        yiDaUtils.forms.instanceIds("FORM-NC966W81ZEV5BRNEAHUXI6725MJ12NKTOZBBL92",
                null,
                null,
                DateUtils.format(modifiedFromTimeGMT, "yyyy-MM-dd HH:mm:ss"),
                null,
                id -> {
                    try {
                        GetFormDataByIDResponseBody data = yiDaUtils.forms.getById(id);
                        consumer.accept(data);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                },
                SearchCondition.textEq("textField_lben36ay", "0")
        );
    }

    /**
     * 宜搭库存数据
     * @param warehouseName {@link String} 仓库名称
     * @return {@link List}<{@link InventoryStatementVo}>
     */
    @SuppressWarnings("unchecked")
    static List<InventoryStatementVo> inventoryStatementFromYiDa(String warehouseName) {
        List<String> list = yiDaUtils.forms.instanceIds("FORM-NC966W81ZEV5BRNEAHUXI6725MJ12NKTOZBBL92",
                SearchCondition.textEq("textField_lben36ay", "0"),
                SearchCondition.textEq("textField_lbbzp1q3", warehouseName));
        return list.stream()
                .map(id -> {
                    System.out.println("抓取" + id + " 当前时间 " + LocalDateTime.now());
                    return yiDaUtils.forms.getById(id);
                })
                .map(vo -> InventoryStatementVo.from((Map<String, Object>) vo.getFormData()))
                .collect(Collectors.toList());
    }

//    /**
//     * 从宜搭更新库存到旺店通
//     * @param warehouse {@link WarehouseYiDaVo}
//     * @param warehouse {@link InventoryStatementVo}
//     */
//    static void updateInventoryStatementFromYiDaToWdt(WarehouseYiDaVo warehouse) {
//        //从宜搭获取对应仓库的所有商品库存信息
//        List<InventoryStatementVo> vos = inventoryStatementFromYiDa(warehouse.getName());
//        //按500条一组分组
//        List<List<InventoryStatementVo>> lists = ListUtils.partition(vos, 500);
//        //每500条组合成一次请求发送到旺店通
//        lists.stream()
//                .map(list -> BeanUtils.copyProperties(YdInventoryStatement.class, list))
//                .forEach(voList -> wmsStockPdStockSyncByPdToWdt(warehouse.getNo(), voList));
//    }

//    /**
//     * 从宜搭更新库存到旺店通
//     * @param warehouse {@link WarehouseYiDaVo}
//     * @param warehouse {@link InventoryStatementVo}
//     */
//    static void updateInventoryStatementFromYiDaToWdt(WarehouseYiDaVo warehouse) {
//        //从宜搭获取对应仓库的所有商品库存信息
//        List<InventoryStatementVo> vos = inventoryStatementFromYiDa(warehouse.getName());
//        //按500条一组分组
//        List<List<InventoryStatementVo>> lists = ListUtils.partition(vos, 500);
//        //每500条组合成一次请求发送到旺店通
//        lists.stream()
//                .map(list -> BeanUtils.copyProperties(YdInventoryStatement.class, list))
//                .forEach(voList -> wmsStockPdStockSyncByPdToWdt(warehouse.getNo(), voList));
//    }

    public static void main(String[] args) {
        System.out.println("开始时间: " + LocalDateTime.now());
        deleteYiDaUtils(LocalDate.of(2023, 8, 7), LocalDate.of(2023, 9, 21));
        deleteYiDaUtilsGroupByWarehouseNo(LocalDate.of(2023, 8, 7), LocalDate.of(2023, 9, 21));
//        yiDaUtils.forms.deleteByIds();
//        updateInventoryStatementFromYiDaToWdt(new WarehouseYiDaVo("038", "洋浩线边仓"));
        System.out.println("结束时间: " + LocalDateTime.now());

//        form(null);
//        List<WarehouseYiDaVo> warehouses = warehouses();
//        System.out.println(warehouses);
//        System.out.println(LocalDateTime.now());
//        List<InventoryStatementVo> form = inventoryStatementFromYiDa("洋浩线边仓");
//        List<List<InventoryStatementVo>> lists = ListUtils.partition(form, 500);
//        for (List<InventoryStatementVo> list : lists) {
//            wmsStockPdStockSyncByPdToWdt(new WarehouseYiDaVo("038", "洋浩线边仓"), list);
//        }
//        CJtUtils.inventoryClassCreate()
//        warehouses.forEach(item -> {
//            System.out.println(item);
//            List<InventoryStatementVo> vos = form(item.getName());
//            System.out.println(vos);
//        });

//        System.out.println(vos);

//        System.out.println(warehouses);
//        GetFormDataByIDResponseBody forms = YdApi.yiDaUtils.forms.getById("FINST-23B66DB1WTTAD4HO9PKXP84MA3YY2UIOLAQHLTQ1");
//        System.out.println(JsonUtils.toJson(forms));
//        getFromIds();
    }

//    public static void main(String[] args) {
//
//    }

    /**
     * 将对应仓库的库存数据组织成一条旺店通盘点单传入
     * @param warehouseNo {@link String} 仓库编号
     * @param inventoryStatementVoList {@link YdInventoryStatement}
     */
    static void wmsStockPdStockSyncByPdToWdt(String warehouseNo, List<YdInventoryStatement> inventoryStatementVoList) {
        if ( !CollectionUtils.isEmpty(inventoryStatementVoList) ) {
            WmsStockStockSyncByPdAo.PdOrder order = new WmsStockStockSyncByPdAo.PdOrder(warehouseNo);
            WmsStockStockSyncByPdAo.SpecList[] array = inventoryStatementVoList.stream().map(tmp -> {
                WmsStockStockSyncByPdAo.SpecList list = new WmsStockStockSyncByPdAo.SpecList();
                list.setDefect(Boolean.FALSE);
                list.setRemark("宜搭库存表同步");
                list.setSpec_no(tmp.getMerchantCode());
                String newNum = tmp.getInventory().toString();
                if ( tmp.getInventory().compareTo(BigDecimal.ZERO) < 0 )
                    newNum = BigDecimal.ZERO.toString();
                list.setNew_num(newNum);
                return list;
            }).toArray(WmsStockStockSyncByPdAo.SpecList[]::new);
            WdtUtils.wmsStockPdStockSyncByPd(order, array);
        }
    }

}
